<?php

if( !defined( 'APP_ROOT' ) ){ echo 'Direct Access Deny!'; return; }

use enums\HttpServerEnums;

use libraries\Verify;
use helpers\Benchmark;
use libraries\RQueue;
use libraries\DExclusiveLock;
use apis\Sms;
use helpers\CommUtils;
use libraries\RedisSession;

use enums\AppEnums;
use enums\ServiceEnums;
use apis\EMail;

// Set the models cache service
$di->set( ServiceEnums::SERVICE_MODELS_CACHE, function (){
	
    $frontCache = new \Phalcon\Cache\Frontend\Data( $this['cacheCfg']->redisCache->frontend->toArray() );
    $cache = new \Phalcon\Cache\Backend\Redis( $frontCache, $this['cacheCfg']->redisCache->backend->toArray() );
	return $cache;
});


$di->set( ServiceEnums::SERVICE_BENCHMARK, function(){
    
    $bm = new Benchmark();
    return $bm;
}, true);


$di->set( ServiceEnums::SERVICE_COOKIES, function()
{


    if( CommUtils::getServerType() == HttpServerEnums::SERVER_TYPE_COMMON )
	{
		$cookies = new \Phalcon\Http\Response\Cookies();
		// 		$cookies = new \libraries\CookiesCommon();
	}
	else
	{
		$cookies = new \libraries\CookiesSwoole();
		$cookies->setDI( $this );
	}

//	$cookies->useEncryption( true );

	//  	ini_set( 'session.cookie_path', 1 );
	return $cookies;
});


$di->set( ServiceEnums::SERVICE_SESSION, function(){

    ini_set( 'session.name', HttpServerEnums::SESSION_KEY );
    ini_set("session.cookie_httponly", 1);
    switch( $this['sessionCfg']->server )
    {
        case \enums\SystemEnums::SESSION_ADAPTER_REDIS:

            if( !extension_loaded( 'redis' ))
            {
                echo 'redis extension not loaded!<br>';

                return null;
            }

            $redisServerCfg = $this['sessionCfg']->{$this['sessionCfg']->server};
            if( CommUtils::getServerType() == HttpServerEnums::SERVER_TYPE_COMMON )
            {
                $session = new \Phalcon\Session\Adapter\Redis( $redisServerCfg->toArray());
                $session->start();

            }
            else
            {//$config->cache->htmlCache->frontend
                $redis = new \Redis();
                $redis->connect( $redisServerCfg->host, $redisServerCfg->port );
                $redis->auth( $redisServerCfg->auth );
                $redis->select( $redisServerCfg->index );

                $this->redisSession = $redis;
                $session = new RedisSession( $this );
            }
            break;

        case \enums\SystemEnums::SESSION_ADAPTER_FILE:
            $session = new \Phalcon\Session\Adapter\Files();
            $session->start();

            break;

    }

    return $session;
}, true );
	
	
$di->set( 'crypt', function(){
	$crypt = new \Phalcon\Crypt();
	$crypt->setKey('#1f135j8$=dah1ak(#@%1V$asdf'); // Use your own key!
	return $crypt;
});
		
// Registering a router
$di->set( ServiceEnums::SERVICE_ROUTER,function (){
    
    require APP_ROOT . 'config/router.php';
    return $router;
}, true );

// Registering unitTest
$di->set( ServiceEnums::SERVICE_UNIT_TEST, function (){
    return new \libraries\UnitTest();
}, true );

$di->set( 'url', function (){
    
    $url = new Phalcon\Mvc\Url();
    $url->setBaseUri( $this['config']->application->baseUri );
    
    return $url;
}, true );

// 验证码
$di->set( ServiceEnums::SERVICE_VERIFY, function (){
    
    $verify = new Verify( $this->di );
    return $verify;
}, true );

// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// cache
/**
 * for html segment
 */
$di->set( ServiceEnums::SERVICE_HTML_CACHE,  function (){

    if( !file_exists( $this['cacheCfg']->htmlCache->backend->cacheDir . 'html/' ) &&
        !mkdir( $this['cacheCfg']->htmlCache->backend->cacheDir . 'html/' ) )
    {
        var_dump( error_get_last() );
        return;
    }

    $frontCache = new \Phalcon\Cache\Frontend\Output( $this['cacheCfg']->htmlCache->frontend->toArray() ); // cache two days
    
    $cache = new \Phalcon\Cache\Backend\File( $frontCache, $this['cacheCfg']->htmlCache->backend->toArray() );
    return $cache;
}, true );



/**
 * memory 易失性 不能进行序列化 只能在一次请求中有效
 */
$di->set( 'memory', function (){
    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $this['cacheCfg']->inmem->frontend->toArray() );

    $cache = new \Phalcon\Cache\Backend\Memory( $frontCache );

    return $cache;
}, true );

$di->set( ServiceEnums::SERVICE_DATA_CACHE, function() {
	if( !extension_loaded( 'redis' ))
	{
		return 'redis extension not loaded!<br>';
	}

	$frontCache = new \Phalcon\Cache\FrontEnd\Data( $this['cacheCfg']->redisCache->frontend->toArray() );
	$cache = new \Phalcon\Cache\Backend\Redis( $frontCache, $this['cacheCfg']->redisCache->backend->toArray() );

	return $cache;
});

/**
 * redis cache
 */
$di->set( ServiceEnums::SERVICE_REDIS_CACHE, function(){
    $frontCache = new \Phalcon\Cache\FrontEnd\Data( $this['cacheCfg']->redisCache->frontend->toArray() );

    $cache = new \Phalcon\Cache\Backend\Redis( $frontCache, $this['cacheCfg']->redisCache->backend->toArray() );

    return $cache;
}, true );

/**
 * native redis
 * 原生native使用phpredis扩展
 */
$di->set( ServiceEnums::SERVICE_NATIVE_REDIS, function()
{
	$redis = new \Redis();
	$redis->connect( $this['cacheCfg']->redisCache->backend->host, $this['cacheCfg']->redisCache->backend->port );
	$redis->auth( $this['cacheCfg']->redisCache->backend->auth );
	$redis->select( $this['cacheCfg']->redisCache->backend->index );
	return $redis;
}, true );



$di->set( 'modelsMetadata',function(){ 
    
	$metaData = new \Phalcon\Mvc\Model\MetaData\Memory( array( 'lifetime' => 1440,  'prefix' => 'metadata_' ));
	
	return $metaData;
}, true );


/**
 * CsrfCheck
 */
$di->set( ServiceEnums::SERVICE_SECURITY, function(){
    
    return new \libraries\CsrfCheck();
}, true );
    
    
$arrLogs = array( ServiceEnums::SERVICE_LOG_BIZ,
    ServiceEnums::SERVICE_LOG_DEBUG,
    ServiceEnums::SERVICE_LOG_ERR,
    ServiceEnums::SERVICE_LOG_INFO
);

foreach( $arrLogs as $log )
{
   $di->set( $log, function() use ($log) {
       
       $strLogPath = $this['logCfg']->log->{$log};
       
       if( !file_exists( $strLogPath ))
       {
           $logFile = fopen( $strLogPath, 'a' );
       
           if( false !== $logFile )
           {
               fclose( $logFile );
           }
           else
           {//error
                return null;
           }
       }
       
       $logger = new Phalcon\Logger\Adapter\File( $strLogPath );
       return $logger;
   });
}